package com.mongo.secret;

import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

import static com.mongo.util.SecretFactory.DES_SECRET;

/**
 * 提供Des加解密
 *
 * @author xiazhun
 * @create 2022/9/20
 */
@NoArgsConstructor
public class Des implements Secret {

    private static volatile Des INSTANCE;

    public static Des getInstance() {
        if (INSTANCE == null) {
            //同步
            synchronized (Des.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Des();
                }
            }
        }
        return INSTANCE;
    }

    @Override
    public String encrypt(String data, String key) {
        String res;
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks;
            if (StringUtils.isBlank(key)) {
                dks = new DESKeySpec(DES_SECRET.getBytes());
            } else {
                dks = new DESKeySpec(key.getBytes());
            }
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
            byte[] bytes = cipher.doFinal(data.getBytes());
            Base64.Encoder encoder = Base64.getEncoder();
            res = encoder.encodeToString(bytes);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
        return res;
    }

    @Override
    public String decode(String data, String key) {
        String res;
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            byte[] buf = decoder.decode(data);
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks;
            if (StringUtils.isBlank(key)) {
                dks = new DESKeySpec(DES_SECRET.getBytes());
            } else {
                dks = new DESKeySpec(key.getBytes());
            }
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(dks);

            Cipher cipher = Cipher.getInstance("DES");

            cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
            byte[] bytes = cipher.doFinal(buf);
            res = new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
        return res;
    }
}
